package com.app.business;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import jxl.Sheet;
import jxl.Workbook;
import com.app.dto.ItemSkuDTO;
import com.app.taobao.RequestTaoBao;
import com.utils.Constants;
import com.utils.UtilsExcel;
import com.utils.UtilsFile;
import com.utils.UtilsLog;
import com.utils.UtilsString;
import com.taobao.api.ApiException;
import com.taobao.api.request.ItemAddRequest;
import com.taobao.api.response.ItemAddResponse;

public class ReadExcelAndRequestTaobao {
	
	
	public void execute(File file){
		Map<String, String> itemsMap = null ;
		Map<String, ItemSkuDTO> skuMap = null;
		Map<String, String> sizeMap = null;
		Sheet itemsSheet = null;
		Sheet skuSheet = null;
		Sheet sizeSheet = null;
		
		Workbook workBook = UtilsExcel.readExcel(file);
		Sheet[] sheets = workBook.getSheets();
		for (Sheet sheet : sheets) {
			String sheetName = sheet.getName();
			if(sheetName.equals("sku表") || sheetName.equals("SKU表") || sheetName.equalsIgnoreCase("sku")){
				skuSheet = sheet;
			}else if(sheetName.equals("属性表")){
				itemsSheet = sheet;
			}else if(sheetName.equals("尺寸表")){
				sizeSheet = sheet;
			}
			if(itemsSheet != null && skuSheet != null && sizeSheet != null) break;
		}
		
		File generateLogFile = null;
		try {
			generateLogFile = UtilsFile.generateLogFile();
			Constants.USER_LOG = generateLogFile.getName();
		} catch (IOException e) {
			UtilsLog.LOG.error("auto generateLogfile Exception!");
		}
		
		RequestTaoBao requestTaoBao = new RequestTaoBao();
		if(itemsSheet != null){
			ReadProSheet read1 = new ReadProSheet();
			itemsMap = read1.getItemsMap(itemsSheet, generateLogFile);
			
			if(skuSheet != null){
				ReadSkuSheet read2 = new ReadSkuSheet();
				skuMap = read2.getSkuMap(itemsMap, skuSheet);
			}
			
			if(sizeSheet != null){
				ReadSizeSheet read3 = new ReadSizeSheet();
				sizeMap = read3.getSizeMap(sizeSheet);
			}
			
			Set<Entry<String, String>> entrySet = itemsMap.entrySet();
			int pri = 0;
			String[] price = null;
			for (Entry<String, String> entry : entrySet) {
				String key = entry.getKey();
				String value = entry.getValue();
				ItemAddRequest req=new ItemAddRequest();
				req.setNum(1L);
				req.setPrice(pri+"");
				req.setType("fixed");
				req.setStuffStatus("new");
				req.setLocationState("浙江");
				req.setLocationCity("杭州");
//				req.setFreightPayer("buyer");
				req.setHasInvoice(true);
				req.setHasWarranty(true);
				req.setValidThru(14L);
				req.setCid(Long.valueOf(UtilsString.parseTagBody(value, "cid")));
				req.setInputStr(UtilsString.parseTagBody(value, "input_str"));
				req.setInputPids(UtilsString.parseTagBody(value, "input_pids"));
				req.setOuterId(key);
				req.setTitle(req.getOuterId() + " " + UtilsString.parseTagBody(value, "title"));
				req.setDesc(req.getTitle());
				req.setApproveStatus("instock");
				
				if(skuSheet != null){
					ItemSkuDTO itemSkuDTO = skuMap.get(key);
					if(itemSkuDTO == null){
						UtilsLog.LOG.warn("警告： " + key + "此商品无sku属性！未添加！");
						break;
					}else{
						price = itemSkuDTO.getSkuPrices().split(",");
						for (String string : price) {
							pri = pri + Integer.parseInt(string);
						}
						pri = pri/price.length;
						req.setPrice(pri+"");
						req.setProps(UtilsString.parseTagBody(value, "props") + itemSkuDTO.getProps());
						req.setSkuOuterIds(itemSkuDTO.getSkuOuterIds());
						req.setSkuPrices(itemSkuDTO.getSkuPrices());
						req.setSkuQuantities(itemSkuDTO.getSkuQuantities());
						req.setSkuProperties(itemSkuDTO.getSkuProperties());
						req.setPropertyAlias(itemSkuDTO.getPropertyAlias());
					}
				}
				
				if(sizeSheet != null && sizeMap.containsKey(key)){
					req.setDesc(sizeMap.get(key));
				}
				
				/*{{
				 * 	
				}}*/
				System.out.println(key + "-------" + req.getCid());
				System.out.println(value);
				System.out.println(req.getProps());
				System.out.println(req.getSkuProperties());
				System.out.println(req.getSkuQuantities());
				System.out.println(req.getPropertyAlias());
				System.out.println(req.getDesc());
//				try {
//					ItemAddResponse resp = requestTaoBao.itemAddRequest(req);
//					if(resp.getErrorCode() == null){
//						UtilsFile.LogToFile(generateLogFile, key + "   已完成！", true);
//					}else{
//						UtilsFile.LogToFile(generateLogFile, key + "   操作失败. " + resp.getMsg() + resp.getSubMsg(), true);
//					}
//				} catch (ApiException e) {
//					//还会有有=xml^_^HTTP_ERROR_200^_^connect timed out 异常
//					if(e.getClass().getName().equals("java.net.SocketTimeoutException")){
//						UtilsFile.LogToFile(generateLogFile, key + ": 操作失败，请求淘宝超时.", true);
//					}else{
//						UtilsFile.LogToFile(generateLogFile, key + ": 操作失败" + e.getMessage(), true);
//					}
//					continue;
//				}
				
				pri = 0;
			}
		}else if(sizeSheet != null){
			ReadSizeSheet read3 = new ReadSizeSheet();
			sizeMap = read3.getSizeMap(sizeSheet);
			Set<Entry<String, String>> entrySet = sizeMap.entrySet();
			try {
				for (Entry<String, String> entry : entrySet) {
					try {
						requestTaoBao.itemUpdateDescByOuterId(entry.getKey(), entry.getValue(), false);
					} catch (ApiException e) {
						if(e.getClass().getName().equals("java.net.SocketTimeoutException")){
							UtilsFile.LogToFile(generateLogFile, entry.getKey() + ": 操作失败，请求淘宝超时." , true);
						}else{
							UtilsFile.LogToFile(generateLogFile, entry.getKey() + ": 操作失败" + e.getMessage() , true);
						}
						continue;
					}
					UtilsFile.LogToFile(generateLogFile, entry.getKey() + "   已完成！", true);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
//		else if(skuSheet != null){
//			ReadSkuSheet read2 = new ReadSkuSheet();
//			skuMap = read2.getSkuMap(itemsMap, skuSheet);
//			Set<Entry<String, ItemSkuDTO>> entrySet = skuMap.entrySet();
//			for (Entry<String, ItemSkuDTO> entry : entrySet) {
//				try {
//					requestTaoBao.SkusQuantityUpdateRequestByOuterID(entry.getKey(), entry.getValue().getOuteridQuantities());
//				} catch (ApiException e) {
//					if(e.getClass().getName().equals("java.net.SocketTimeoutException")){
//						UtilsFile.LogToFile(generateLogFile, entry.getKey() + ": 操作失败，请求淘宝超时." , true);
//					}else{
//						UtilsFile.LogToFile(generateLogFile, entry.getKey() + ": 操作失败" + e.getMessage() , true);
//					}
//					
//					continue;
//				}
//				UtilsFile.LogToFile(generateLogFile, entry.getKey()+"   已完成！", true);
//			}
//		}
		
		UtilsFile.LogToFile(generateLogFile, "[over!]", true);
		
		workBook.close();// 关闭
	}

	
}